package no7;

import java.net.*;
import org.junit.Test;
import java.io.*;

/*
 *主机名：DESKTOP-IT2L5SV
 *本地IP地址：192.168.56.1
*/

public class TCPTest1 {
	@Test
	public void client() {
		InetAddress inet = null;
		Socket socket = null;
		OutputStream os = null;
		try {
			inet = InetAddress.getByName("192.168.56.1");
			socket = new Socket(inet, 8899);
			os = socket.getOutputStream();
			os.write("我是你爸爸hh".getBytes());
		} catch(IOException e)  {
			e.printStackTrace();
		} finally {
			if(os != null) {
				try {
					os.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
			if(socket != null) {
				try {
					socket.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@Test
	public void server() {
		ServerSocket ss = null;
		Socket socket = null;
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		try {
			//1.创建服务器端的ServerSocket，指明自己的端口号
			ss = new ServerSocket(8899);
			//2.接受来自于客户端的socket
			socket = ss.accept();
			//3.获取输入流
			is = socket.getInputStream();
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[5];
			int len;
			while((len = is.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			System.out.println(baos.toString());
			System.out.println("收到了来自于：" + socket.getInetAddress().getHostAddress() + "的数据");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			//4.资源关闭
			if(ss != null) {
				try {
					ss.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
			if(socket != null) {
				try {
					socket.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
			if(is != null) {
				try {
					is.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
			if(baos != null) {
				try {
					baos.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

